package com.fzg.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fzg.common.enums.ResponseWrapper;
import com.fzg.common.tool.HttpUtils;
import com.fzg.common.tool.ImageCodeTool;
import com.fzg.common.tool.JSONUtilsTool;
import com.fzg.entity.Gedan;
import com.fzg.entity.Gequ;
import com.fzg.mapper.GedanMapper;
import com.fzg.mapper.GequMapper;
import com.fzg.service.GequService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 歌单的歌曲 服务实现类
 * </p>
 *
 * @author fzg
 * @since 2022-12-05
 */

@Slf4j
@Service
public class GequServiceImpl extends ServiceImpl<GequMapper, Gequ> implements GequService {

    @Autowired
    private GequMapper gequMapper;

    @Autowired
    private GedanMapper gedanMapper;

    /**
     * 获取歌单列表之后
     * 请求url：获取歌单的所有歌曲
     * http://localhost:3000/playlist/track/all?id=24381616&limit=30
     * 传入歌单id，获取每张歌单30首歌曲
     * 保存数据库
     */
    @Override
    public ResponseWrapper getGeDanAllSongs() {
        ArrayList<StringBuilder> res = new ArrayList<>();
        // 数据库获取歌单
        List<Gedan> gedanList = gedanMapper.selectList(null);
        if (gedanList.size() > 0){
            for (Gedan gedan : gedanList) {
                // 根据歌单的id，请求获取歌曲30首
                ArrayList<Gequ> geQuList = getGeQuListByGeDanId(gedan.getId());
                if (geQuList.size() > 0){
                    StringBuilder message = new StringBuilder();
                    message.append("歌单: ").append(gedan.getName()).append("的歌曲获取成功");
                    for (Gequ gequ : geQuList) {
                        Gequ gequ1 = gequMapper.selectOne(new LambdaQueryWrapper<Gequ>().eq(Gequ::getId, gequ.getId()));
                        if (gequ1 == null){
                            gequMapper.insert(gequ);
                        }
                    }
                    message.append("----------数据库保存成功");
                    res.add(message);
                }else {
                    res.add(new StringBuilder("歌单：" + gedan.getName() + "的歌曲没获取到"));
                }
            }
            return ResponseWrapper.markSuccess(res);
        }else {
            return ResponseWrapper.markCustomError("数据库歌单数据为空");
        }
    }

    /**
     * 数据库查出歌曲列表
     * 根据歌曲的图片url
     * 下载图片到本地
     */
    @Override
    public ResponseWrapper downLoadSongsImg() {
        // 开始计时
        Timestamp startTime = new Timestamp(System.currentTimeMillis());
        List<Gequ> gequList = gequMapper.selectList(null);
        if (gequList.size() > 0){
            String path = "E:\\pictures\\wangyiyun-imgs\\songs-imgs";
            ArrayList<StringBuilder> res = new ArrayList<>();
            for (Gequ gequ : gequList) {
                StringBuilder message = new StringBuilder();
                String name = "song" + gequ.getId();
                String url = gequ.getPicUrl();
                File file = new File(path + "\\" + name);
                if (file.exists()){
                    message.append("歌曲：").append(gequ.getName()).append(" 图片已存在");
                }else {
                    try {
                        ImageCodeTool.download(url,name,path);
                        message.append("歌曲：").append(gequ.getName()).append(" 图片下载成功");
                    } catch (Exception e) {
                        message.append("歌曲：").append(gequ.getName()).append(" 图片下载失败");
                        e.printStackTrace();
                    }
                }
                res.add(message);
            }
            // 结束计时
            Timestamp endTime = new Timestamp(System.currentTimeMillis());
            // 用时
            long second = (endTime.getTime() - startTime.getTime()) / 1000;
            long minute = (endTime.getTime() - startTime.getTime()) / 1000 / 60;
            log.info("用时：" + second + "秒；");
            if (minute >= 1) {
                log.info("用时：" + minute + "分钟");
            }
            return ResponseWrapper.markCustomSuccess("歌曲图片下载成功",res);
        }else {
            return ResponseWrapper.markCustomError("歌曲列表为空");
        }
    }


    /**
     * 根据歌单id获取30首歌曲
     * @param geDanId 歌单id
     * @return ArrayList<Gequ>
     */
    public ArrayList<Gequ> getGeQuListByGeDanId(Long geDanId){
        ArrayList<Gequ> gequs = new ArrayList<>();
        String url = "http://localhost:3000/playlist/track/all?id=" + geDanId + "&limit=30";
        String s = HttpUtils.sendGetRequest(url);
        Map<String, Object> map = JSONUtilsTool.JSONObjectToMap(JSONObject.parseObject(s));
        if (map.get("code").equals(200)){
            String songs = map.get("songs").toString();
            JSONArray songArr = JSONObject.parseArray(songs);
            for (Object o : songArr) {
                Map<String, Object> itemMap = JSONUtilsTool.JSONObjectToMap(JSONObject.parseObject(o.toString()));
                Map<String, Object> alMap = JSONUtilsTool.JSONObjectToMap(JSONObject.parseObject(itemMap.get("al").toString()));
                Gequ gequ = new Gequ();
                gequ.setId(Long.parseLong(alMap.get("id").toString()));
                gequ.setName(alMap.get("name").toString());
                gequ.setPicUrl(alMap.get("picUrl").toString());
                gequ.setGedanId(geDanId);
                gequs.add(gequ);
            }
            return gequs;
        }else {
            return new ArrayList<>();
        }
    }


    public static void main(String[] args) {
        String url = "http://localhost:3000/playlist/track/all?id=2235097256&limit=30";
        String s = HttpUtils.sendGetRequest(url);
        log.info(s);
        Map<String, Object> map = JSONUtilsTool.JSONObjectToMap(JSONObject.parseObject(s));
        if (map.get("code").equals(200)){
            String songs = map.get("songs").toString();
            JSONArray songArr = JSONObject.parseArray(songs);
            for (Object o : songArr) {
                Map<String, Object> itemMap = JSONUtilsTool.JSONObjectToMap(JSONObject.parseObject(o.toString()));
                Map<String, Object> alMap = JSONUtilsTool.JSONObjectToMap(JSONObject.parseObject(itemMap.get("al").toString()));
                log.info(alMap.get("picUrl").toString());
            }
        }
    }
}
